package com.cskaoyan.controller;

import com.cskaoyan.bean.MarketAd;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.AdData;
import com.cskaoyan.exception.ValidationException;
import com.cskaoyan.service.AdService;
import com.cskaoyan.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;


/**
 * 广告管理
 * @author Fyy
 * @since 2022/12/28 17:28
 */
@RequestMapping("admin/ad")
@RestController
public class AdController {

    @Autowired
    AdService adService;

    /**
     *广告管理页面
     * @param basePageInfo
     * @param name
     * @param content
     * @return
     */
    @RequestMapping("list")
    public BaseRespVo list(BasePageInfo basePageInfo, String name, String content){
        CommonData<MarketAd> data = adService.queryAll(basePageInfo,name,content);
        return BaseRespVo.ok(data);
    }

    /**
     * 新建广告
     * @param marketAd
     * @return
     */
    @RequestMapping("create")
    public BaseRespVo create(@RequestBody @Valid MarketAd marketAd, BindingResult bindingResult) throws ValidationException {
        ValidationUtil.valid(bindingResult);
        //设置添加时间
        marketAd.setAddTime(new Date());
        //设置修改时间
        marketAd.setUpdateTime(new Date());
        //新增广告
        adService.create(marketAd);
        //给返回值中的data赋值
        AdData data = AdData.data(marketAd);
        BaseRespVo respVo = BaseRespVo.ok(data);
        respVo.setErrmsg("成功");
        return respVo;
    }

    /**
     * 修改广告
     * @param marketAd
     * @return
     */
    @RequestMapping("update")
    public BaseRespVo update(@RequestBody @Valid MarketAd marketAd, BindingResult bindingResult) throws ValidationException {
        //设置改动时间
        ValidationUtil.valid(bindingResult);
        marketAd.setUpdateTime(new Date());
        adService.update(marketAd);
        AdData data = AdData.data(marketAd);
        BaseRespVo respVo = BaseRespVo.ok(data);
        respVo.setErrmsg("成功");
        return respVo;
    }

    /**
     * 删除广告
     * @param marketAd
     * @return
     */
    @RequestMapping("delete")
    public BaseRespVo delete(@RequestBody MarketAd marketAd){
        adService.delete(marketAd);
        return BaseRespVo.ok();
    }
}
